<?php


class Message_Data_Mapper
{
    
private $result = null;
private $errors = null;
    
    public function save( Message_Model $model)
    {
        $db = Db_Helper::getInstance();
        $sql = "
                INSERT INTO messages (fromId, sendToId, data, timeCreated)
                VALUES(
                    '" . $model->getFromId()  . "',
                    '" . $model->getSendToId()  . "',
                    '" . $model->getData()  . "',
                    '" . $model->getTimeCreated()  . "'
                    )";
        if(!$db->insert($sql)) {
            $this->errors = QUERY_ERROR;
            return false;
        } else {
            return true;
        }                        
    }
    
    
    public function fetchAll($userId, $page = 1 ,$limit = 10)
    {
        $db = Db_Helper::getInstance();
        $sql = "   
                    SELECT id , fromId, sendToId, data, readed ,timeCreated
                    FROM messages
                    WHERE fromId= " . $userId . " OR sendToId= "  .  $userId .  " AND authorSee=1 AND toWhoSee=1
                    ORDER BY id DESC
                    LIMIT " . --$page * $limit . " , " . $limit . "
                    ";
        $arrayMessageModels = $db->selectAll($sql, 'Message_Model');
        if(!$arrayMessageModels){
            $this->errors = NO_MESSAGES_ERROR;
            return false;
        }  else {
            // то что ниже для того чтобы сделать только 2 запроса к бд а не 10 !!!!!
            foreach($arrayMessageModels as $k=>$v){
                $arr[] = $v->getFromId();
                $arr[] = $v->getSendToId();
            }
            $arr = array_unique($arr);
            $sql2 = "
                     SELECT id,login,firstName,secondName 
                     FROM users
                     WHERE id IN (" .  implode(',', $arr) . ")"
                    ;
            $arrayUserModels = $db->selectAll($sql2, 'User_Model');
            if(!$arrayUserModels){
                $this->errors = QUERY_ERROR;
                return false;
            } else {
                foreach($arrayMessageModels as $k=>$v) {
                    foreach($arrayUserModels as $kk=>$vv){
                         if($vv->getId() == $v->getFromId()) {
                             $v->setFromName($vv->getFirstName() . ' ' . $vv->getSecondName());
                         } else if($vv->getId() == $v->getSendToId()){
                             $v->setToWhoName($vv->getFirstName() . ' ' . $vv->getSecondName());;
                         }
                    }
                }
                return $arrayMessageModels; 
            }   
        }
    }
    
    public function countAllMessages($userId)
    {
        $db = Db_Helper::getInstance();
        $sql = "   
                    SELECT COUNT(id)
                    FROM messages
                    WHERE fromId = " . $userId  .   " OR sendToId = " . $userId
                    ;
        $row = $db->select($sql);
        if(!$row){
            $this->errors = QUERY_ERROR;
            return false;
        } else {
            return $row['COUNT(id)'];
        }   
    }
    
    public function fetchOne($userId, $id)
    {
        $db = Db_Helper::getInstance();
        $sql = "
                SELECT id , fromId, sendToId, data ,timeCreated
                FROM messages
                WHERE id=" . $id .  " AND authorSee=1 AND toWhoSee=1 AND fromId=" . $userId . " 
                ||    id=" . $id .  " AND authorSee=1 AND toWhoSee=1 AND sendToId=" . $userId . "
                LIMIT 1
                ";
        $row = $db->select($sql) ;          
        if(!$row) {
            $this->errors = NO_ACEESS_ERROR;
            return false; 
        } else {
            $model = new Message_Model($row);
            // достает из таблицы юзеров их имена
            $arr[] = $model->getFromId();
            $arr[] = $model->getSendToId();
            $sql2 = "
                     SELECT id,login,firstName,secondName 
                     FROM users
                     WHERE id IN (" .  implode(',', $arr) . ")"
                    ;
            $arrayUserModels = $db->selectAll($sql2, 'User_Model');
            if(!$arrayUserModels){
                $this->errors = QUERY_ERROR;
                return false;
            } else {
                foreach($arrayUserModels as $k=>$v){
                    if($v->getId() == $model->getFromId()) {
                        $model->setFromName($v->getFirstName() . ' ' . $v->getSecondName());
                    } else if($v->getId() == $model->getSendToId()){
                        $model->setToWhoName($v->getFirstName() . ' ' . $v->getSecondName());;
                    }
                }
                //добавить статус isMyMessage
                if($model->getFromId() == $userId){
                    $model->setIsMyMessage(true);
                }
               // убирает статус непрочитанного сообщения 
               if(null == $model->getReaded() && $userId == $model->getSendToId() ){
                    $sql3 = "
                             UPDATE messages 
                             SET readed = 1 
                             WHERE id = " .  $id
                    ;
                   $row2 = $db->update($sql3) ;
                   if(!$row2) {
                       $this->errors = QUERY_ERROR;
                       return false;
                   } else{
                       return $model; 
                   }
               } else {
                   return $model;
               }                          
            }
        }       
    }
    
    public function sendHelloMessage( Message_Model $model)
    {
        $db = Db_Helper::getInstance();
        $sql = "INSERT INTO messages (fromId, sendToId, data, timeCreated) 
                VALUES(
                        '" . SUPPORT_ID_IN_DB . "',
                        '" . $model->getSendToId()  .  "',
                        '" . NEW_USER_WELCOME_MESSAGE . "',
                        '" . $model->getTimeCreated()  .  "'
                )";
        if(!$db->insert($sql)) {
            $this->errors = QUERY_ERROR ;
            return false;
        } else {
            return true;
        }
    }
    
    public function getErrors()
    {
       return $this->errors; 
    }
    
       
}
